package version3.part1.common.serializer.MyCode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;
import version3.part1.common.Message.MessageType;
import version3.part1.common.Message.RpcRequest;
import version3.part1.common.Message.RpcResponse;
import version3.part1.common.serializer.MySerializer.Serializer;

@AllArgsConstructor
public class MyEncoder extends MessageToByteEncoder{
    private Serializer serializer;

    /**
     * @param ctx 上下文
     * @param msg 要编码的消息对象
     * @param out 输出缓冲区，用于存储编码后的消息
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        System.out.println(msg.getClass().getName());
        // 构造消息，消息类型-序列化类型-数据长度-数据
        if(msg instanceof RpcRequest){
            out.writeShort(MessageType.REQUEST.getCode());
        }
        if(msg instanceof RpcResponse){
            out.writeShort(MessageType.RESPONSE.getCode());
        }
        out.writeShort(serializer.getType());
        byte[] bytes = serializer.serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);

    }
}
